#!/usr/bin/env python
#coding=utf-8

import xml.dom.minidom
import codecs
import os

def getUserRecord(userID, filePath = 'd:/Statistics.xml'):
    
    #判断文件是否存在
    if not os.path.exists(filePath):
        print 'No such file: ', filePath
        return -1
    
    dom = xml.dom.minidom.parse(filePath)
    root = dom.documentElement

    #获取用户胜负信息
    win = 0
    lose = 0
    userlist = root.getElementsByTagName('user')
    for user in userlist:
        if cmp(user.getAttribute('id'), userID) == 0:
            win = int(user.getAttribute('win'))
            lose = int(user.getAttribute('lose'))
            break
    return [win, lose]


def setUserRecord(userID, isWin, filePath = 'd:/Statistics.xml'):
    
    #判断文件是否存在
    if not os.path.exists(filePath):
        print 'No such file: ', filePath
        return False
    
    dom = xml.dom.minidom.parse(filePath)
    root = dom.documentElement
    #print root.toxml()
    
    #设置用户胜负信息
    userlist = root.getElementsByTagName('user')
    inUserList = False
    for user in userlist:
        if cmp(user.getAttribute('id'), userID) == 0:
            inUserList = True
            if isWin:
                win = int(user.getAttribute('win'))
                user.setAttribute('win', unicode(win + 1))
            else:
                lose = int(user.getAttribute('lose'))
                user.setAttribute('lose', unicode(lose + 1))
            break
    if not inUserList:
        newuser = dom.createElement('user')
        newuser.setAttribute('id', userID)
        if isWin:
            newuser.setAttribute('win', '1')
            newuser.setAttribute('lose', '0')
        else:
            newuser.setAttribute('win', '0')
            newuser.setAttribute('lose', '1')
        root.appendChild(newuser)
    print root.toxml()
    
    #保存xml文件
    try:
        f = file(filePath, 'w')
        writer = codecs.lookup('utf-8')[3](f)
        dom.writexml(writer, encoding = 'utf-8')
        writer.close()
    except:
        return False
    finally:
        f.close()
        return True

if __name__ == '__main__':
    #print setUserRecord('2', True)
    print getUserRecord('3')